package com.teacher.hong.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Enumeration;

@Slf4j
@WebServlet("/myHttpPost")
public class MyHttpPostServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //在一些核心的业务代码里面
        System.out.println("sout....");
        log.trace("trace...参数age:" + req.getParameter("age"));
        log.debug("debug...参数sex:" + req.getParameter("sex"));
        log.info("info...参数name:" + req.getParameter("name"));
        log.warn("warn...");
        log.error("error...");


//        Enumeration<String> names = req.getParameterNames();
//        while (names.hasMoreElements()) {
//            String name = names.nextElement();  //获取参数名称
//            System.out.println("参数" + name + ",\t值：" + req.getParameter(name));
//        }

        ServletUtils.recordVisits(getServletContext());

        /**
         * 操作了一堆我们代码
         */
        JSONObject object = new JSONObject();
        object.put("state", 200);

        JSONArray values = new JSONArray();
        JSONObject value1 = new JSONObject();
        value1.put("id", 1001);
        value1.put("name", "jack");
        value1.put("age", 20);
        value1.put("sex", "男");
        values.add(value1);
        JSONObject value2 = new JSONObject();
        value2.put("id", 1002);
        value2.put("name", "rose");
        value2.put("age", 18);
        value2.put("sex", "女");
        values.add(value2);

        object.put("value", values);
        object.put("timestamp", LocalDateTime.now());

        resp.setContentType("application/json");
        resp.getWriter().write(object.toJSONString());



    }

}
